<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use think\Db;

/**
 * 系统接口
 */
class System extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 协议
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="user_content", type="string", required=true, sample="返回成功",description="用户协议")
     * @ApiReturnParams   (name="privacy_content", type="string", required=true, sample="返回成功",description="隐私协议")
     */
    public function getUserContent()
    {
        if($this->auth->id){
            $user = DB::name("user")->where("id",$this->auth->id)->find();
            $lang_type = $user['lang_type'];
        }else{
            $lang_type = 1;
        }
        $result = DB::name("system_info")->where("type",$lang_type)->field("user_content,privacy_content,bang_content")->find();
        $this->success('', $result);
    }
    
    /**
     * 普通分享内容
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="user_content", type="string", required=true, sample="返回成功",description="用户协议")
     * @ApiReturnParams   (name="privacy_content", type="string", required=true, sample="返回成功",description="隐私协议")
     */
    public function getSystemShare()
    {
        if($this->auth->id){
            $user = DB::name("user")->where("id",$this->auth->id)->find();
            $lang_type = $user['lang_type'];
        }else{
            $lang_type = 1;
        }
        $result = DB::name("system_info")->where("type",$lang_type)->field("share_title,share_blurb,share_image")->select();
        if(empty($result['title'])){
            $result = DB::name("system_share")->where("lang_type",$lang_type)->field("share_title,share_blurb,share_image")->select();
        }
        $this->success('查询成功', $result);
    }
    
    /**
     * 充值配置
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="user_content", type="string", required=true, sample="返回成功",description="用户协议")
     * @ApiReturnParams   (name="privacy_content", type="string", required=true, sample="返回成功",description="隐私协议")
     */
    public function getSystemRecharge()
    {
        $user_find = DB::name("user")->where("id",$this->auth->id)->find();

        if(empty($user_find['level_type'])){
            $level_type = 2;
        }else {
            $level_type = $user_find['level_type'];
        }

//        $result = DB::name("system_recharge")->where("level_type",$level_type)->order("weigh desc")->select();
        $result = DB::name("system_recharge")->whereIn("id",[20,18])->order("weigh desc")->select();
        $this->success('', $result);
    }
    
     /**
     * 视频配置
     * @param string $type 类型:1=微信小程序,2=抖音小程序,3=app,4=h5,5=其他
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="user_content", type="string", required=true, sample="返回成功",description="用户协议")
     * @ApiReturnParams   (name="privacy_content", type="string", required=true, sample="返回成功",description="隐私协议")
     */
    public function getSystemVideo()
    {
        $type = input("type")?input("type"):1;
        $result = DB::name("system_video")->where("type",$type)->find();
        $source = input("source");
        if($source == 1){
            if($result['media_id']){
                $access_token = $this->get_access_token();
                $url = 'https://api.weixin.qq.com/wxa/sec/vod/getmedialink?access_token='.$access_token;
                $data = array(
                    "media_id" => $result['media_id'],
                    "t" => time()+3600
                );
                //这里要把传递的参数给转成json，不然小程序接口会报数据类型错误。
                $res = json_decode($this->json_post($url,$data),true);

                //如果是40001，说明access_token过期失效了，必须强制获取最新的access_token
                if($res['errcode'] == '40001'){
                    $access_token = $this->get_latest_access_token();
                    $url = 'https://api.weixin.qq.com/wxa/sec/vod/getmedialink?access_token='.$access_token;
                    $data = array(
                        "media_id" => $result['media_id'],
                        "t" => time()+3600
                    );
                    //这里要把传递的参数给转成json，不然小程序接口会报数据类型错误。
                    $res = json_decode($this->json_post($url,$data),true);
                }

                if($res['errcode'] == '0'){
                    $media_info = $res['media_info'];
                    $result['file'] = $media_info['mp4_url'];
                }else {
                    file_put_contents("systemvideo.txt","errcode={$res['errcode']},errmsg={$res['errmsg']},access_token={$access_token},media_id={$data['media_id']},t={$data['t']}".PHP_EOL,FILE_APPEND);
                }
            }
        }
        $this->success('查询成功', $result);
    }

    /**
     * 帮助与反馈列表
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     */
    public function getSystemHelpsList()
    {
        if($this->auth->id){
            $user = DB::name("user")->where("id",$this->auth->id)->find();
            $lang_type = $user['lang_type'];
        }else{
            $lang_type = 1;
        }
        $result = DB::name("system_helps")->where("type",$lang_type)->order("weigh desc")->select();
        $this->success('查询成功', $result);
    }
    
     /**
     * 帮助与反馈详情
     * @param string $system_helps_id  帮助与反馈id
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     */
    public function getSystemHelpsDetail()
    {
        $system_helps_id = input("system_helps_id");
        $where = array("id"=>$system_helps_id);
        
        $result = DB::name("system_helps")->where($where)->find();
        
        $this->success('查询成功', $result);
    }
    
     /**
     * 等级配置
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="name", type="string", required=true, sample="返回成功",description="等级名称")
     * @ApiReturnParams   (name="eng_name", type="string", required=true, sample="返回成功",description="英文等级名称")
     * @ApiReturnParams   (name="ri_name", type="string", required=true, sample="返回成功",description="日文等级名称")
     * @ApiReturnParams   (name="han_name", type="string", required=true, sample="返回成功",description="韩文等级名称")
     * @ApiReturnParams   (name="level", type="string", required=true, sample="返回成功",description="等级")
     * @ApiReturnParams   (name="image", type="string", required=true, sample="返回成功",description="等级图标")
     * @ApiReturnParams   (name="money", type="string", required=true, sample="返回成功",description="达标充值数")
     * @ApiReturnParams   (name="blurb", type="string", required=true, sample="返回成功",description="等级介绍")
     * @ApiReturnParams   (name="eng_blurb", type="string", required=true, sample="返回成功",description="英文介绍")
     * @ApiReturnParams   (name="ri_blurb", type="string", required=true, sample="返回成功",description="日文介绍")
     * @ApiReturnParams   (name="han_blurb", type="string", required=true, sample="返回成功",description="韩文介绍")
     * @ApiReturnParams   (name="advertdata", type="string", required=true, sample="返回成功",description="跳过广告:1=是,2=否")
     * @ApiReturnParams   (name="displaydata", type="string", required=true, sample="返回成功",description="展示等级:1=是,2=否")
     * @ApiReturnParams   (name="give", type="string", required=true, sample="返回成功",description="赠送嘶豆")
     */
    public function getSystemLevel()
    {
        $result = DB::name("system_level")->order("level asc")->select();
        $this->success('查询成功', $result);
    }
    
    
    /**
     * 任务配置
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="day_signin_num", type="string", required=true, sample="返回成功",description="签到得嘶豆")
     * @ApiReturnParams   (name="three_signin_num", type="string", required=true, sample="返回成功",description="三日签到得嘶豆")
     * @ApiReturnParams   (name="seven_signin_num", type="string", required=true, sample="返回成功",description="七日签到得嘶豆")
     * @ApiReturnParams   (name="share_num", type="string", required=true, sample="返回成功",description="每日首次分享得嘶豆")
     * @ApiReturnParams   (name="barrage_num", type="string", required=true, sample="返回成功",description="每日首次弹幕得嘶豆")
     * @ApiReturnParams   (name="look_num", type="string", required=true, sample="返回成功",description="每日浏览10分钟得嘶豆")
     * @ApiReturnParams   (name="signin_num", type="string", required=true, sample="返回成功",description="连续签到天数")
     * @ApiReturnParams   (name="day_signin", type="string", required=true, sample="返回成功",description="当日签到：1=已得，2=未得")
     * @ApiReturnParams   (name="day_share", type="string", required=true, sample="返回成功",description="当日分享：1=已得，2=未得")
     * @ApiReturnParams   (name="day_barrage", type="string", required=true, sample="返回成功",description="当日弹幕：1=已得，2=未得")
     * @ApiReturnParams   (name="day_look", type="string", required=true, sample="返回成功",description="当日浏览10分钟：1=已得，2=未得")
     */
    public function getSystemTask()
    {
        $result = DB::name("system_task")->find();

        $user = DB::name("user")->where("id",$this->auth->id)->find();

        if($user['signin_num'] == 7){
            //签到7天,从第一天开始
            $result['signin_num'] = 0;
        }else{
            //签到不足7天
            // 前一天的时间
            $yesterdayTime = strtotime("-1 day", time());
            // 格式化前一天的时间为Y-m-d H:i:s格式
            $yesterdayDate = date("Y-m-d", $yesterdayTime);
            $yester_user_task = Db::name('user_task')->where("(type = 1 or type = 2 or type = 3) and user_id = ".$this->auth->id." and (create_time like '%".$yesterdayDate."%' or create_time like '%".date("Y-m-d")."%')")->find();
            // echo "(type = 1 or type = 2 or type = 3) and user_id = ".$this->auth->id." and create_time like '%".$yesterdayDate."%'";exit;
            // echo "type = 1 and create_time like '%".$yesterdayDate."%'";exit;
            if($yester_user_task){
                $result['signin_num'] = $user['signin_num'];
            }else{
                $result['signin_num'] = 0;
            }
        }
        $user_signin = Db::name('user_task')->where("(type = 1 or type = 2 or type = 3) and user_id = ".$this->auth->id." and create_time like '%".date("Y-m-d")."%'")->find();
        if($user_signin){
            $result["day_signin"] = 1;
        }else{
            $result["day_signin"] = 2;
        }
        $user_share = Db::name('user_task')->where("type = 4 and user_id = ".$this->auth->id." and create_time like '%".date("Y-m-d")."%'")->find();
        if($user_share){
            $result["day_share"] = 1;
        }else{
            $result["day_share"] = 2;
        }
        $user_barrage = Db::name('user_task')->where("type = 5 and user_id = ".$this->auth->id." and create_time like '%".date("Y-m-d")."%'")->find();
        if($user_barrage){
            $result["day_barrage"] = 1;
        }else{
            $result["day_barrage"] = 2;
        }
        $user_look = Db::name('user_task')->where("type = 6 and user_id = ".$this->auth->id." and create_time like '%".date("Y-m-d")."%'")->find();
        if($user_look){
            $result["day_look"] = 1;
        }else{
            $result["day_look"] = 2;
        }
        $this->success('查询成功', $result);
    }
    
    public function doJisuanChannel()
    {
        
        $result = DB::name("user_channel")->select();
        $today = date("Y-m-d");
        $yester_day = date("Y-m-d", strtotime("-1 day"));
        foreach($result as $key => $val){
            //昨日投流推广数
            $yester_where = "user_channel_id =".$val['id']." and create_time like '%".$yester_day."%'";
            $yester_channel_num = DB::name("channel_log")->where($yester_where)->count();
            //今日投流推广数
            $totay_where = "user_channel_id =".$val['id']." and create_time like '%".$today."%'";
            $today_channel_num = DB::name("channel_log")->where($totay_where)->count();

            //昨日充值推广数
            $yester_recharge_where = "user_channel_id =".$val['id']." and status = 2 and create_time like '%".$yester_day."%'";
            $yester_recharge_channel_count = DB::name("user_recharge")->where($yester_recharge_where)->count();
            $yester_recharge_channel_money = DB::name("user_recharge")->where($yester_recharge_where)->sum("money");
            //今日充值推广数
            $totay_recharge_where = "user_channel_id =".$val['id']." and status = 2 and create_time like '%".$today."%'";
            $today_recharge_channel_num = DB::name("user_recharge")->where($totay_recharge_where)->count();
            $today_recharge_channel_money = DB::name("user_recharge")->where($totay_recharge_where)->sum("money");
            $data = array(
                "money" => $today_recharge_channel_money,
                "yester_money" => $yester_recharge_channel_money,
                "today_recharge_num" => $today_recharge_channel_num,
                "yester_recharge_num" => $yester_recharge_channel_count,
                "today_reg_num" => $today_channel_num,
                "yester_reg_num" => $yester_channel_num,
            );
            DB::name("user_channel")->where("id",$val['id'])->update($data);
        }
        echo "SUCCESS";exit;
    }

    /**
     * 由于CPS的表记录的数据量太庞大了，所以只保留最近5天的监测记录
     * fa_cpa_bili表里的数据没有用到，可以删
     * fa_cpa_dou_yin表里的数据没有用到，可以删
     * fa_cpa_teng_xun表里用到了openid和callback，用于回传数据，不能删
     * @return void
     */
    public function deleteCpsLog()
    {
        $time = date('Y-m-d 00:00:00',strtotime("-5 days"));
        $res = DB::name("cpa_dou_yin")->where("create_time","<",$time)->delete();
        $res2 = DB::name("cpa_bili")->where("create_time","<",$time)->delete();
//        echo "清理dy_{$res}条,清理b_{$res2}条";
        echo "SUCCESS";exit;
    }

    
    /**
     * 任务Banner
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="image", type="string", required=true, sample="返回成功",description="轮播图")
     * @ApiReturnParams   (name="images", type="string", required=true, sample="返回成功",description="详情图")
     */
    public function getSystemBanner()
    {
        $result = DB::name("system_banner")->order("weigh desc")->select();
        $this->success('查询成功', $result);
    }

    /**
     * 支付挽留分享的文案内容
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     */
    public function getSystemShareword()
    {
        $result = DB::name("system_shareword")->where('id',1)->find();
        $this->success('查询成功',$result);
    }

}
